package com.itheima.filter;

import com.itheima.exception.BusinessException;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest Request, ServletResponse Response, FilterChain filterChain) throws IOException, ServletException {
        //0.强转对象
        HttpServletRequest req = (HttpServletRequest) Request;
        HttpServletResponse resp = (HttpServletResponse) Response;

        //1.获取请求url。
        StringBuffer url = req.getRequestURL();
        String uri = req.getRequestURI();
        System.out.println("url:"+url);  //http://localhost:8080/login
        System.out.println("uri:"+uri);  ///login

        //2.判断请求url中是否包含login，如果包含，说明是登录操作，放行。
        if(uri.contains("login")){
            //登录操作，放行
            filterChain.doFilter(Request,Response);
            //【注意】结束当前请求
            return;
        }


        //3.获取请求头中的令牌（token）。
        String token = req.getHeader("token");

        //4.判断令牌是否存在，如果不存在，响应401。
        if(token == null){
            resp.setStatus(401);
            System.out.println("令牌为空");
            //throw new BusinessException("未登录，请先登录");
            return;
        }

        //5.解析token，如果解析失败，响应401 。
        try {
            Claims claims = JwtUtils.parseJWT(token);
            System.out.println("claims = " + claims);
        } catch (Exception e) {
            resp.setStatus(401);
            System.out.println("令牌解析失败"+ e.getMessage());
            //throw new BusinessException("未登录，请先登录");
            return;
        }

        //6.放行。
        filterChain.doFilter(Request,Response);
    }
}
